<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">
          <img
            src="http://likede2-admin.itheima.net/img/logo.595745bd.png"
            alt=""
          >
        </h3>
      </div>

      <el-form-item prop="loginName">
        <div class="svg-container">
          <!-- <svg-icon icon-class="user" /> -->
          <i class="el-icon-mobile-phone" />
        </div>
        <el-input
          ref="loginName"
          v-model.trim="loginForm.loginName"
          placeholder="请输入账号"
          name="loginName"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <!-- <svg-icon icon-class="password" /> -->
          <i class="el-icon-lock" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model.trim="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
        />
        <!-- 显示密码 -->
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="code">
        <div class="svg-container">
          <!-- <svg-icon icon-class="user" /> -->
          <!-- <i class="el-icon-mobile-phone" /> -->
          <i class="iconfont icon-security" />
        </div>
        <el-input
          ref="code"
          v-model="loginForm.code"
          maxlength="4"
          placeholder="请输入验证码"
          name="code"
          type="text"
          tabindex="1"
          @keyup.enter.native="handleLogin"
        />
        <img :src="imgRandom" alt="" @click="randomImage">
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
      >登录</el-button>

      <!-- <div class="tips">
        <span style="margin-right: 20px">username: admin</span>
        <span> password: any</span>
      </div> -->
    </el-form>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import { imageValid } from '@/api/user'

export default {
  name: 'Login',
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   if (!validUsername(value)) {
    //     callback(new Error('Please enter the correct user name'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      loginForm: {
        loginName: 'admin',
        password: 'admin',
        code: '',
        clientToken: ''
      },
      loginRules: {
        loginName: [
          { required: true, trigger: ['blur', 'change'], message: '请输入账户' },
          { max: 18, trigger: ['blur', 'change'], message: '账号限制输入18个字符以内' }
        ],
        password: [
          { required: true, trigger: ['blur', 'change'], message: '请输入密码' },
          { min: 1, max: 20, trigger: ['blur', 'change'], message: '密码限制输入1-20个字符' }
        ],
        // 验证码
        code: [
          { required: true, trigger: ['blur', 'change'], message: '请输入验证码' }
        ]
      },
      loading: false,
      passwordType: 'password',
      code: '',
      imgRandom: '' // 验证码图片
      // clientToken: ''
    }
  },
  created() {
    this.randomImage() // 每次进入页面获取随机验证码
  },
  methods: {
    // 登录校验
    async handleLogin() {
      // this.$refs.loginForm.validate((a, b) => {
      //   // 第一个参数代表是否校验成功，第二个参数是未通过的字段
      //   console.log(a, b)
      //   this.$message.success('添加成功')
      // })
      try {
        this.loading = true
        await this.$refs.loginForm.validate()
        await this.$store.dispatch('user/loginAction', this.loginForm)
        // this.$message.success('登录成功')
        this.$router.push('/')
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
      // try {
      //   const valid = await this.$refs.loginForm.validate()
      //   console.log(valid)
      //   if (valid) {
      //     const res = await login({
      //       clientToken: this.clientToken,
      //       code: this.loginForm.code,
      //       password: this.loginForm.password,
      //       loginName: this.loginForm.loginName
      //     })
      //     console.log(res)
      //     if (res.data.success) {
      //       this.$message.success('登录成功')
      //       this.loading = true // 登录按钮加载中
      //       // 将token保存到vuex中
      //       this.$store.commit('user/setUserToken', res.data.token)
      //       this.$router.push('/') // 跳转
      //       this.loading = false
      //     } else if (res.data.msg === '验证码错误') {
      //       this.$message.error('验证码错误')
      //     } else if (res.data.msg === '账户名或密码错误') {
      //       this.$message.error('账户名或密码错误')
      //     }
      //   }
      // } catch (err) {
      //   console.error(err)
      // }
    },
    // 随机验证码
    async randomImage() {
      this.loginForm.clientToken = this.randomString(32)
      // this.clientToken = Math.floor(Math.random() * 10).toString()
      const res = await imageValid(this.loginForm.clientToken)
      // console.log(res)
      // console.log('获取随机验证码成功')
      // 将乱码 图片转换成 base64
      const buffer = Buffer.from(res, 'base64')
      const base64Str = 'data:image/png;base64,' + buffer.toString('base64')
      this.imgRandom = base64Str
      // this.$nextTick(() => {
      //   this.$refs.imgRandom.src = base64Str
      // })
    },
    // 显示密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 随机数
    randomString(len, charSet) {
      charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      var randomString = ''
      for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length)
        randomString += charSet.substring(randomPoz, randomPoz + 1)
      }
      return randomString
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background-image: url("http://likede2-admin.itheima.net/img/background.be4fae7d.png");
  background-size: cover;
  .el-button {
    width: 100%;
    height: 52px;
    background: linear-gradient(262deg,#2e50e1,#6878f0);
    opacity: .91;
    border-radius: 8px;
    color: #fff;
    text-shadow: 0 7px 22px #cfcfcf;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      height: 47px;
      background: transparent;
      border: 0;
      border-radius: 0;
      padding: 12px 5px 12px 15px;
      color: #999;
      caret-color: #999;
      -webkit-appearance: none;
    }
  }

  .el-form-item {
    position: relative;
    width: 100%;
    height: 52px;
    margin-bottom: 24px;
    background: #fff;
    border: 1px solid #e2e2e2;
    border-radius: 4px;
    img {
      position: absolute;
      right: 0;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: absolute;
    width: 518px;
    height: 388px;
    top: 50%;
    left: 50%;
    margin-top: -194px;
    margin-left: -259px;
    padding: 36px 35px 0;
    background: #fff;
    -webkit-box-shadow: 0 3px 70px 0 rgb(30 111 72 / 35%);
    box-shadow: 0 3px 70px 0 rgb(30 111 72 / 35%);
    border-radius: 10px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    i {
      // display: inline-block;
      width:16px;
      height:16px;
      color: inherit;
    }
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      img {
        position: absolute;
        width: 96px;
        height: 96px;
        top: -122px;
        left: 50%;
        margin-left: -48px;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
